<?php
class ProductTypesController extends AppController {
	var $name = 'ProductTypes';
	var $components = array('Init', 'Param');

	function beforeFilter() {
		if (!$this->Session->read('admin')) {
			$this->redirect('/login');
		}
		else {
			$this->Init->startup($this);
			$this->Admin = $this->Init->init();

			$this->set('dashboard',0);
			$this->set('content',0);
			$this->set('products',1);
			$this->set('component',0);
			$this->set('system',0);

			$this->set('title','Categories Management');
			$this->set('sub_title', $this->Param->getAction($this->params));
  		}
	}

	function index(){
		$this->paginate = array(
			'ProductType' => array(
				'conditions' => array(
					'ProductType.status' => 1
				),
				'limit' => 10,
				'order'	=> array('ProductType.parent asc','ProductType.sort asc')
			)
		);

		$category = $this->paginate('ProductType');

		for ($i=0; $i < count($category); $i++) {
			if ($category[$i]['ProductType']['parent'] != 0) {
				$parent = $this->ProductType->get($category[$i]['ProductType']['parent']);
				$category[$i]['ProductType']['parent_name'] = $parent['ProductType']['name_eng'];
			}
			else {
				$category[$i]['ProductType']['parent_name'] = 'Root';
			}
		}
		$this->set('category',$category);
	}

	function edit($id = null) {
		$this->helpers[] = 'Ck';
		$id = $this->Param->getID($this->params);

		if (isset($this->data)) {
			$this->data['ProductType']['sort'] = intval($this->data['ProductType']['sort']);
			$this->data['ProductType']['date'] = date('Y-m-d H:i:s');
			$this->data['ProductType']['name'] = trim(strip_tags($this->data['ProductType']['name']));

			if(!empty($_FILES['upload']['name'])) {

				App::import('Component', 'Upload');
				$upload = new UploadComponent();
				$upload->setPath('categories');
				$_error = $upload->checkImage($_FILES['upload']['size']);

				if(empty($_error)) {
					$_file = $upload->upload($_FILES['upload'], $id);
					$this->data['ProductType']['img'] = $_file;
				}
				else {
					$this->Session->setFlash($_error);
					$this->redirect('/product_types');
				}
			}

			if ($this->ProductType->save($this->data)) {
				$this->Session->setFlash('Done successfully!');
				$this->redirect('/product_types');
			}

		}
		else {
			if (isset($id) && ($id > 0)) {
				$this->data = $this->ProductType->find('first',array(
					'conditions' => array('ProductType.id' => $id)
				));
				$this->set('parent', $this->data['ProductType']['parent']);
			}
			else {
				$this->set('parent', 0);
			}
		}

		$categories = $this->ProductType->getList();
		$categories['0'] = 'Root';
		$this->set('categories',$categories);
	}

	function del($id = null) {
		$id = $this->Param->getID($this->params);
		 $this->ProductType->id = $id;
		 $this->ProductType->delete();
		 $this->Session->setFlash('Done successfully');
		 $this->redirect('/product_types');
	}

}
?>